package com.igeek.boot.config;

import cn.hutool.core.util.ObjectUtil;
import com.igeek.boot.entity.Admin;
import com.igeek.boot.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Author fengqq
 * @Description UserDetailsService 是security提供的自定义 基于数据库查询 认证用户信息的接口
 * @Date 2024/9/13  15:29
 */
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IAdminService adminService;
    //根据用户名 查询 认证用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.findAdminByName(username);
        if(ObjectUtil.isEmpty(admin)){
            throw  new RuntimeException("用户名或者密码错误");
        }
        LoginUser loginUser = new LoginUser(admin);

        // 将Authentication对象（用户信息、已认证状态、权限信息）存入security上下文 SecurityContextHolder （后续登录成功后 某个功能需要获取当前登录人信息 则直接从security上下文来获取）
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return loginUser;
    }
}
